const utils = require('./utils');
const bent = require('bent');
const fs = require('fs');
const path = require('path');
const defaultConfig = require('./defaultConfig');
const loaderUtils = require('loader-utils');
const isDev = utils.isDevelop();
const map = new Set();
const CONFIG_NAME = defaultConfig.configName;
const isExistConfig = fs.existsSync(CONFIG_NAME);
const chalk = require('chalk');

module.exports = function (source) {
  // console.log('-------picthc-------', remainingRequest, precedingRequest, data)
  const resource = this.resource;
  const options = loaderUtils.getOptions(this);
  // console.log('---------------', resource)
  // if (/\.vue\?vue&type=template/.test(resource)) {
  if (/\.vue/.test(resource)) {
    const str = source.replace(/<!--(.|[\r\n])*?-->/g, ''); //去除注释
    const config = utils.getConfig(isExistConfig, options);
    if (isExistConfig) {
      const dir = path.resolve(CONFIG_NAME);
      this.addDependency(dir);
    }

    const { componentTag } = config;
    const workName = path.basename(process.cwd()); //当前工程名称
    const downloadImage = async function (name) {
      try {
        if (map.has(name)) { //TODO 使用map判断缓存的缺点是多线程时无法共享内存
          return;
        }
        map.add(name);

        const remotePath = config.remotePath;
        const url = path.join(remotePath, name + '.svg' + (isDev ? '' : `?name=${workName}`));
        let stream = await bent(url)();
        const svgPath = utils.getSvgPath();
        const write = fs.createWriteStream(path.resolve(svgPath, name + '.svg'));
        stream.pipe(write);
        console.log();
        console.log(chalk(`下载图标【${chalk.green(name)}】成功！`));
      } catch (e) {
        console.error(chalk(`下载图标【${chalk.red(name)}】失败！原因是：【${chalk.red(e.message)}】`));
        map.delete(name);
        if (!utils.isDevelop()) {
          process.exit(1);
        }
      }
    };

    const downloadImages = async function (iconNames) {
      // console.log(iconNames)
      const svgPath = utils.getSvgPath();
      await utils.mkdir(svgPath);
      return Promise.all(iconNames.map(downloadImage));
    };

    const reg = new RegExp(`<${componentTag}\\s.*name="([\\w-]*)"`);
    const iconNames = [];
    if (reg.test(str)) {
      const reg2 = new RegExp(`<${componentTag}\\s.*name="([\\w-]*)"`, 'g');
      const getIcons = function (str, reg2) {
        const arr = [];
        str.replace(reg2, function (rs, $1) {
          arr.push($1);
        });
        return arr;
      };
      iconNames.push(...getIcons(str, reg2));
    }

    //处理三元表达式
    //类似 <kiss-font :name="isicon ? 'go': 'search'" /> 与  <kiss-font :name="!isicon ? 'go': 'search'" /> 
    //正则为：/<kiss-font\s.*:name="[\s]?[\w!]+[\s]?\?[\s]?'(\w+)'[\s]?:[\s]?'(\w+)'"/;
    const reg3 = new RegExp(`<${componentTag}.*\\s:name="[\\s]?[\\w!]+[\\s]?\\?[\\s]?'(\\w+)'[\\s]?:[\\s]?'(\\w+)'"`);
    if (reg3.test(str)) {
      const reg4 = new RegExp(`<${componentTag}.*\\s:name="[\\s]?[\\w!]+[\\s]?\\?[\\s]?'(\\w+)'[\\s]?:[\\s]?'(\\w+)'"`, 'g');

      const getIcons = function (str, reg) {
        const arr = [];
        str.replace(reg, function (rs, $1, $2) {
          arr.push($1);
          arr.push($2);
        });
        return arr;
      };
      iconNames.push(...getIcons(str, reg4));
    }

    if (iconNames.length > 0) {
      if (Array.isArray(config.files)) {
        iconNames.push(...config.files);
      }
      var callback = this.async();
      downloadImages(iconNames).then(() => {
        callback(null, str);
      });
      return;
    }
  }

  return source;
};